<template>
  <base-modal :show.sync="visible" width="600px" class="base-export-modal base-export-modal-group">
    <!-- start 分组 -->
    <template slot="title">
      <h3 v-if="isShowExportTip">
        {{ $t('component.baseExport.title') }}
        <el-tooltip placement="top">
          <template slot="content">
            {{ $t('component.baseExport.tooltip') }}
            <span class="export-link" @click="toExport">{{ $t('component.baseExport.toImport') }}</span>
          </template>
          <i class="iconfont icon-warning-circle-fill task-icon icon-color"></i>
        </el-tooltip>
      </h3>
      <h3 v-else>
        {{ $t('component.baseExport.title') }}
      </h3>
    </template>
    <div>
      <el-checkbox v-model="isCheckedAll" @change="toggle">{{ $t('common.base.selectAll') }}</el-checkbox>
      <el-checkbox-group v-model="checkedGroupArr" @change="handleChangeGroup" style="width: 100%" class="base-export-field-wrap">
        <template>
          <el-checkbox v-for="col in filterColumns" :key="getUUID(col)" :label="col.value">
            {{ col.label }}
          </el-checkbox>
        </template>
      </el-checkbox-group>
    </div>

    <div class="base-export-modal-content" v-if="needchooseBreak">
      <div class="base-export-modal-title">
        {{ $t('component.baseExport.exportOption') }}
      </div>
      <el-checkbox v-model="tooltip" class="base-export-field-wrap export-option-checkbox" :title="$t('component.baseExport.exportOptionCheckboxTitle')">{{ $t('component.baseExport.exportOptionCheckbox') }}</el-checkbox>
    </div>
    <div class="base-export-modal-content" v-for="item in filterColumns" :key="getUUID(item)">
      <div class="base-export-modal-title">
        {{ item.label }}
      </div>

      <el-checkbox-group v-if="checkedMap[item.value]" v-model="checkedMap[item.value]" @change="handleChange" style="width: 100%" class="base-export-field-wrap">
        <template>
          <el-checkbox v-for="(col, index) in item.columns" :key="`${col.field}_${index}`" v-if="!col.bool" :label="col.exportAlias ? col.exportAlias : col.field" @change="handleCheckboxChildChange($event, item)">
            {{ col.label }}
            <div class="tooltip" v-if="(item.value === 'taskChecked' || item.value === 'eventChecked') && (col.formType === 'select' || col.formType === 'connector') && col.setting.isMulti">{{ $t('common.base.multipleRowsData') }}</div>
            <div class="tooltip" v-if="(item.value === 'receiptChecked' || item.value === 'eventReceiptChecked') && col.formType === 'select' && col.setting.isMulti">{{ $t('common.base.multipleRowsData') }}</div>
            <div class="tooltip" v-if="(item.value === 'receiptChecked' || item.value === 'eventReceiptChecked') && (col.fieldName === 'spare_name' || col.fieldName === 'apply_material' || col.fieldName === 'return_material' || col.fieldName === 'service_name' || (col.formType === 'connector'&& col.setting.isMulti))">{{ $t('common.base.multipleRowsData') }}</div>
            <div class="tooltip" v-if="item.value === 'systemChecked' && (col.fieldName === 'executorTag' || col.fieldName === 'synergies')">{{ $t('common.base.multipleRowsData') }}</div>
            <div class="tooltip" v-if="item.value === `annexChecked${index}` && col.inputType == 'multiple'">{{ $t('common.base.multipleRowsData') }}</div>
            <div class="tooltip" v-if="item.value === `annexChecked${index}` && col.inputType == 'single' && col.formType == 'selectMulti'">{{ $t('common.base.multipleRowsData') }}</div>
          </el-checkbox>
        </template>
      </el-checkbox-group>
    </div>
    <!-- end 分组 -->

    <div slot="footer" class="export-footer">
      <div class="export-footer-left">
        <template v-if="isShowCustomTips">
          <i class="iconfont icon-charts"></i>
          <span>{{ $t('frame.backgroundTask.text23') }}</span>
          <a @click="toCustomChart" class="btn-link" href="javascript:;">{{ $t('frame.backgroundTask.text24') }}</a>
        </template>
      </div>

      <div class="export-footer-right">
        <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" :disabled="pending" @click="exportData(true)">
          {{ pending ? $t('common.base.exporting') : $t('common.base.export') }}
        </el-button>
      </div>
    </div>

    <div class="base-export-bridge" ref="bridge"></div>
  </base-modal>
</template>

<script>
import { t } from '@src/locales';
import baseExportMixin from '@src/mixins/baseExportMixin';
import { isEmpty } from '@src/util/type';
import { uuid } from 'pub-bbx-utils';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { getRootWindowInitData } from '@src/util/window'
const rootWindowInitData = getRootWindowInitData();

export default {
  name: 'base-export-group',
  mixins: [baseExportMixin],
  props: {
    action: String,
    alert: Function,
    buildParams: Function,
    columns: Array,
    downloadUrl: String,
    group: {
      type: Boolean,
      default: false,
    },
    emulateJSON: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: t('component.baseExport.title'),
    },
    method: {
      type: String,
      default: 'get',
    },
    /**
     * 函数必须返回Promise对象
     * 如果验证失败，promise需要返回错误信息，否则返回null
     */
    validate: Function,
    needchooseBreak: {
      type: Boolean | String,
      default: true,
    },
    isShowExportTip: {
      type: Boolean | String,
      default: false,
    },
    storageKey: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      filterColumnsExpandLength: 0,
      filterColumnsExpand: [],
      filterColumnsMap: {},
      checkedMap: {},
      checkedGroupArr: [],
      checkedGroupArrOld: [],
      ids: [],
      fileName: '',
      visible: false,
      pending: false,
      checkedArr: [],
      isCheckedAll: true,
      tooltip: true,
      isDownloadNow: false, // 导出是否是立刻下载模式

      checked: '',
    };
  },
  watch: {
    columns: {
      deep: true,
      handler(value) {
        this.buildCheckedMap(value);
      },
    },
  },
  computed: {
    authorities() {
      return rootWindowInitData?.user?.auth || {};
    },
    isShowCustomTips() {
      return this.authorities?.REPORT_CREATE == 3;
    },
    checkedLength() {
      let checkedMap = this.checkedMap;
      let length = 0;

      for (let key in checkedMap) {
        let columns = checkedMap[key];
        length += columns.length;
      }

      return length;
    },
    filterColumns() {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.filterColumnsExpandLength = 0;
      return this.columns.map(item => {
        let columns = item.columns || [];

        if (Array.isArray(columns) || columns.length < 1) {
          console.warn('Caused: base-export-group filter columns item has no columns');
        }

        item.columns = columns.filter(column => {
          // 拥有filterIsBan字段的统统不允许被过滤
          if (column['filterIsBan']) return true;
          return column.export && column.formType != 'attachment';
        });

        this.filterColumnsExpandLength += item.columns.length;
        this.filterColumnsExpand.push(...item.columns);
        this.filterColumnsMap[item.value] = item.columns;
        return item;
      });
    },
  },
  methods: {
    toExport() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityDepartment,
      });
    },
    buildCheckedMap(columns = []) {
      let checkedMap = {};

      columns.forEach(column => {
        checkedMap[column.value] = [];
      });

      this.checkedMap = checkedMap;
    },
    buildParamsFunc() {
      return typeof this.buildParams == 'function' ? this.buildParams(this.checkedMap, this.ids, this.tooltip) : { checked: this.checkedArr.join(','), ids: this.ids.join(',') };
    },
    checkedAll(checkedAll = true) {
      let checkedMap = this.checkedMap;

      this.checkedGroupArr = [];

      for (let key in checkedMap) {
        let columns = this.filterColumnsMap[key];

        let checkedArr = [];

        if (checkedAll) {
          checkedArr = columns.map(item => (item.exportAlias ? item.exportAlias : item.field));

          this.checkedGroupArr.push(key);
        }

        this.$set(this.checkedMap, key, checkedArr);
      }
      this.checkedGroupArrOld = this.checkedGroupArr;
    },
    getUUID() {
      return uuid();
    },
    handleChange() {
      this.isCheckedAll = this.checkedLength == this.filterColumnsExpandLength;
    },
    handleChangeGroup(value) {
      let checkedMap = this.checkedMap;

      this.checkedGroupArr = [];

      for (let key in checkedMap) {
        let checkedArr = [];

        if (value.indexOf(key) > -1) {
          if (this.checkedGroupArrOld.includes(key)) {
            // 当前key以前全选现在也全选，使用旧值不改变
            checkedArr = checkedMap[key];
          } else {
            // 当前key以前没全选现在全选，重新全部赋值
            let columns = this.filterColumnsMap[key] || [];

            checkedArr = columns.map(item => item.exportAlias || item.field);
          }

          this.checkedGroupArr.push(key);
        } else {
          checkedArr = []
          if (!this.checkedGroupArrOld.includes(key)) {
            // 当前key以前没全选现在也没全选，使用旧值不改变
            checkedArr = checkedMap[key];
          }
        }

        this.$set(this.checkedMap, key, checkedArr);
      }

      this.checkedGroupArrOld = this.checkedGroupArr;

      this.handleChange();
    },
    isCheckedEmpty() {
      return this.filterColumnsExpandLength == 0;
    },
    async open(ids = [], fileName = `${t('common.base.exportData')}.xlsx`, isDownloadNow = false, params = {}) {
      this.pending = false;
      this.ids = ids;
      this.fileName = fileName;

      this.isCheckedAll = true;

      this.buildCheckedMap(this.columns);
      this.checkedAll();
      
      if (this.storageKey !== '') {
        const { checkedMap, checkedGroup, isCheckedAll, tooltip } = await this.getExportStorageData(this.storageKey);
        if (!isEmpty(checkedMap)) {
          this.isCheckedAll = isCheckedAll;
          this.checkedGroupArr = checkedGroup;
          this.checkedGroupArrOld = checkedGroup;
        }

        this.checkedMap = Object.assign(this.checkedMap, checkedMap);
        this.tooltip = tooltip;
      } else {
        let obj = {}
        this.$nextTick(()=>{
          let checkArr = []
          this.columns.forEach(i => {
            let arr = []
            
            i.columns.forEach(i_=>{
                arr.push(i_.field);
            })
            if(arr.length === i.columns.length){
              checkArr.push(i.value)
            }
            
            obj[i.value] = arr;
          
          });
          if(checkArr.length === this.columns.length){
            this.isCheckedAll = true
          }else{
            this.isCheckedAll = false
          }
          this.checkedGroupArr = checkArr
          this.checkedGroupArrOld = checkArr
          this.checkedMap = obj;
        })
        
      }

      this.isDownloadNow = isDownloadNow;

      this.visible = true;
    },
    toggle(value) {
      this.checkedAll(value);
    },
    handleCheckboxChildChange($event, group) {
      const { value = '' } = group;
      // 默认的group item的数组长度
      const defaultGroupItemLength = this.filterColumns.find(item => item.value === value)?.columns?.length || 0;
      // 选中group的长度
      const checkedGroupItemLength = this.checkedMap[value].length;
      // 需要删除的数组下标index
      const needSpliceIndex = this.checkedGroupArr.findIndex(item => item === value);
      // 根据相关选中的长度判断是否小于默认的group的长度判断去删除顶部选中的checkbox Item
      checkedGroupItemLength < defaultGroupItemLength ? needSpliceIndex > -1 && this.checkedGroupArr.splice(needSpliceIndex, 1) : this.checkedGroupArr.push(value);
      // 这里判断是否取消全选的checkbox
      this.isCheckedAll = this.filterColumns.length <= this.checkedGroupArr.length;
    },
    // 跳转自定义报表
    toCustomChart() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomCharts,
        params: `chartType=table&dataset=task`,
        reload: true,
      })
    }
  },
};
</script>

<style lang="scss">
@import './../BaseExport/BaseExport.scss';

.base-export-modal-group {
  .base-export-modal-content {
    margin-top: 10px;
  }

  .base-export-modal-title {
    font-weight: 500;
    font-size: 15px;
    line-height: 30px;
    height: 30px;
  }
  .tooltip {
    background-color: #4472c4;
    margin-left: 3px;
    margin-bottom: 0px;
    padding: 2px 6px;
    color: white;
    display: inline-block;
  }
}
</style>
<style lang="scss" scoped>
.export-link {
  color: $color-primary-light-6;
  cursor: pointer;
  text-decoration: underline;
}
.export-option-checkbox {
  ::v-deep .el-checkbox__label {
    flex: 1;
    white-space: pre-wrap;
  }
}
</style>
